import React, { useState, useEffect } from "react";
import { List, message, Collapse, Spin ,ConfigProvider } from "antd";

import {
  getCrmMailmergeList,
  groupBy,
  getCrmRecordById,
  getCrmRecordFromSql,
  parseWString,
  formatDateToUpper,
  numberToEnglish,
} from "../../util/util";

const { Panel } = Collapse;

//通用打印预览
const App = (pagedata) => {

  // const [templatesList, setTemplatesList] = useState([]);
  const [loading, setLoading] = useState(true);
  const [selectedRow, setSelectedRow] = useState(null);
  const [groupedTemplates, setGroupedTemplates] = useState({
    "发票-分箱分页": [
      {
        id: 222222221,
        isshowdis: true,
        groupbyarrray: ["ContainerNumber"],
        name: "发票-分箱分页发票",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/6oi1dd5d0e981edfb419fb395d41636ac01aa?x-cli-msg={"linkId":"1nHCl5jqnex-31RIu","isFileOwner":false}`,
      },
    ],
    "箱单-分箱分页": [
      {
        id: 322222221,
        isshowdis: false,
        groupbyarrray: ["ContainerNumber"],
        name: "箱单-分箱分页箱单五-标准",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/6oi1d7ebc456ab37a42c1b3337eb8346f021f?x-cli-msg={"linkId":"1nHCl5jqae5-31RIu","isFileOwner":false}`,
      },
      {
        id: 322222222,
        isshowdis: false,
        groupbyarrray: ["ContainerNumber"],
        name: "箱单-分箱分页箱单五-毛重",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/6oi1dd4a8a0001602446cb52b76b22bb963c2?x-cli-msg={"linkId":"1nHCl5jqney-31RIu","isFileOwner":false}`,
      },
      {
        id: 322222223,
        name: "箱单-分箱分页箱单五-毛重方数",
        isdep: true,
        isshowdis: false,
        groupbyarrray: ["ContainerNumber"],
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/6oi1d4bd97cc5e6c04eb99e8b06dc784fca7b?x-cli-msg={"linkId":"1nHCl5jqnez-31RIu","isFileOwner":false}`,
      },
    ],
    "发票-格式二": [
      {
        id: 422222221,
        isshowdis: true,
        groupbyarrray: [],
        name: "发票-格式二-有G.W.",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthr92b56979ab8e4f53b5926cc1f385a245?x-cli-msg={"linkId":"1nHCl5jqrEJ-31RIu","isFileOwner":false}`,
      },
      {
        id: 422222222,
        isshowdis: true,
        groupbyarrray: [],
        name: "发票-格式二-无G.W.",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthrcb275d5ac6c24322b869589c6f2c3c89?x-cli-msg={"linkId":"1nHCl5jqrEK-31RIu","isFileOwner":false}`,
      },
      {
        id: 422222223,
        isshowdis: true,
        groupbyarrray: ["OrderNo"],
        name: "发票-格式二-无G.W.-分页",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthrcb275d5ac6c24322b869589c6f2c3c89?x-cli-msg={"linkId":"1nHCl5jqrEK-31RIu","isFileOwner":false}`,
      },
    ],
    "发票-格式三": [
      {
        id: 722222221,
        isshowdis: true,
        groupbyarrray: [],
        name: "发票-发票-格式三",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthr09ad94007ba44da49630cff000101b99?x-cli-msg={"linkId":"1nHCl5jqwl5-31RIu","isFileOwner":false}`,
      },
      {
        id: 722222222,
        isshowdis: true,
        groupbyarrray: [],
        name: "发票-发票-格式三折扣发票",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthrda32ff66a62341c7a62acb40b056c520?x-cli-msg={"linkId":"1nHCl5jqwl6-31RIu","isFileOwner":false}`,
      },
    ],
    "箱单-箱单二": [
      {
        id: 522222221,
        isshowdis: false,
        groupbyarrray: [],
        name: "箱单-箱单二-有G.W.",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthrdbf952eb119a4ae6ae70d0955248dc5e?x-cli-msg={"linkId":"1nHCl5jqrEL-31RIu","isFileOwner":false}`,
      },
      {
        id: 522222222,
        isshowdis: false,
        groupbyarrray: [],
        name: "箱单-箱单二-标准-无G.W. ",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthra478b3eced054a5da28379c5cb271f9c?x-cli-msg={"linkId":"1nHCl5jqrEM-31RIu","isFileOwner":false}`,
      },
      {
        id: 522222223,
        isshowdis: false,
        groupbyarrray: [],
        name: "箱单-箱单二-有毛净重体积",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthrf48cb6423ed04a2c8e84b660b1bea25c?x-cli-msg={"linkId":"1nHCl5jqrEN-31RIu","isFileOwner":false}`,
      },
    ],
    "箱单-箱单三": [
      {
        id: 822222221,
        isshowdis: false,
        groupbyarrray: [],
        name: "箱单-箱单三-VTK",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthr1982ca3716c744a78775a1acd25d5bcd?x-cli-msg={"linkId":"1nHCl5jqwl7-31RIu","isFileOwner":false}`,
      },
    ],
    "发票-清关发票": [
      {
        id: 622222221,
        isshowdis: false,
        groupbyarrray: [""],
        name: "发票-清关发票-SUMARRY INVOICE",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/kjthre033d1f2839246e1b0af6ec7d39131ee?x-cli-msg={"linkId":"1nHCl5jqrEP-31RIu","isFileOwner":false}`,
      },
    ],
    拟证: [
      {
        id: 122222221,
        name: "拟证",
        isdep: true,
        templateurl: `https://files.zohopublic.com.cn/public/workdrive-public/download/6oi1dcb27fbf3e967489da9268d1f20d93185?x-cli-msg={"linkId":"1nHCl5jqdRT-31RIu","isFileOwner":false}`,
      },
    ],
  });
  // {"data":{"EntityId":["185647000005823112"],"Entity":"Documentmag","ButtonPosition":"DetailView"}}  console.log('pagedata11111',pagedata);
  let Entityname = pagedata?.data?.Entity;
  let dataid = pagedata?.data?.EntityId[0];

  useEffect(() => {

    const fetchData = async () => {
      try {
        setLoading(true);
        const response = await getCrmMailmergeList(Entityname);
        console.log("response", response);
        if (
          response &&
          response.details &&
          response.details.statusMessage &&
          response.details.statusMessage.templates
        ) {
          const templatesArray = response.details.statusMessage.templates
            .filter((item) => item.folder.name !== "停用")
            .map((item) => ({
              ...item,
              filename: item.name.replace(/\.zdoc$/, ""),
            }));
          console.log("templatesArray", templatesArray);

          // 更新面板的默认展开 key
          const tempGroupedTemplates = templatesArray.reduce((acc, item) => {
            const folderName = item.folder.name;
            if (!acc[folderName]) {
              acc[folderName] = [];
            }
            acc[folderName].push(item);
            return acc;
          }, {});

          setGroupedTemplates((prevState) => ({
            ...prevState,
            ...tempGroupedTemplates,
          }));
        }
      } catch (error) {
        console.error("Error fetching data:", error);
      } finally {
        setLoading(false);
      }
    };
    const initialize = async () => {
      await window.zohoReadyPromise;
      console.log("ZOHO is ready", window.ZOHO);
      fetchData();
    };
    initialize();
  }, [Entityname, dataid]);

  //拟证逻辑
  const antiepidemic_print = async (record) => {
    try {
      //1、发票号截取       发票号：ICP24W0375W0376W0377W0384
      //2、根据W号查询厂检合格单
      //3、拿到注册编号，去重分组，一个注册编号一个整数
      //4、动物源性中英文
      //5、调取模板打印拟证
      // console.log('record',`选择${record.name}`);
      var recorddata = await getCrmRecordById(Entityname, dataid);
      if (recorddata) {
        var Antiepidemic_Inv = recorddata?.Antiepidemic_Inv;
        console.log("Antiepidemic_Inv", Antiepidemic_Inv);
        var array_w = parseWString(Antiepidemic_Inv);
        console.log("array_w", array_w);
        if (array_w && array_w.length > 0) {
          // 用于存储结果的 Map
          const resultMap = new Map();

          // 异步操作
          await Promise.all(
            array_w.map(async (w) => {
              var sql = `select WNO, id from FactoryIcd where WNO like '%${w}%'`;
              const result = await getCrmRecordFromSql(sql);
              console.log("result", result);

              if (result) {
                result.forEach((item) => {
                  resultMap.set(item.id, item);
                });
              }
            })
          );

          // 将结果转换为数组
          const uniqueResults = Array.from(resultMap.values());

          console.log("uniqueResults", uniqueResults);
          var datadetail = [];
          for (const n of uniqueResults) {
            console.log("厂检合格单id", n.id);
            var FactoryIcdinfo = await getCrmRecordById("FactoryIcd", n.id);
            console.log("FactoryIcdinfo", FactoryIcdinfo);

            const AnimalOrigin_Cn = extractBakValues(FactoryIcdinfo, "Bak");
            const AnimalOrigin_En = extractBakValues(
              FactoryIcdinfo,
              "AnimalOrigin_En"
            );
            console.log("AnimalOrigin_Cn", AnimalOrigin_Cn);
            console.log("AnimalOrigin_En", AnimalOrigin_En);

            var tempinfo = {
              antiepidemicno: FactoryIcdinfo?.VaccinationcerNo,
              sailingdate: formatDateToUpper(recorddata?.EstimatedShippingDate),
              shipname: recorddata?.VesselVoyage || "",
              blno: recorddata?.BLNo || "",
              VaccinationcerDate: formatDateToUpper(
                FactoryIcdinfo?.VaccinationcerDate || ""
              ),
              nw: recorddata?.TotalNetWeight || "",
              gw: recorddata?.TotalGrossWeight || "",
              boxsealno: recorddata?.ContainerSealNumber || "",
              animalorigin: AnimalOrigin_En.join(","),
              AS: AnimalOrigin_Cn.includes("鸡") || AnimalOrigin_Cn.includes("火鸡") || AnimalOrigin_Cn.includes("鸭"),        //鸡 火鸡 鸭
              RA: (AnimalOrigin_Cn.includes("牛") || AnimalOrigin_Cn.includes("羊")  || AnimalOrigin_Cn.includes("牛皮")) && !AnimalOrigin_Cn.includes("鹿") ,  //牛 羊 不包含鹿
              RAP: AnimalOrigin_Cn.includes("牛皮"),    //牛皮
              RAR : (AnimalOrigin_Cn.includes("鹿") && (!AnimalOrigin_Cn.includes("牛") &&  !AnimalOrigin_Cn.includes("羊") && !AnimalOrigin_Cn.includes("牛皮"))) ,  //鹿
              RAN: AnimalOrigin_Cn.includes("奶") || AnimalOrigin_Cn.includes("奶酪"),      //奶,奶酪
              RAS: AnimalOrigin_Cn.includes("奶") || AnimalOrigin_Cn.includes("奶酪"),    //奶,奶酪
              PA: AnimalOrigin_Cn.includes("鱼") || AnimalOrigin_Cn.includes("真鳕") 
              || AnimalOrigin_Cn.includes("狭鳕") || AnimalOrigin_Cn.includes("三文鱼") 
              || AnimalOrigin_Cn.includes("鱿鱼") || AnimalOrigin_Cn.includes("虾") 
              || AnimalOrigin_Cn.includes("蟹") || AnimalOrigin_Cn.includes("扇贝") 
              || AnimalOrigin_Cn.includes("牡蛎壳") || AnimalOrigin_Cn.includes("虾蟹壳") || AnimalOrigin_Cn.includes("金枪鱼"),      //鱼 真鳕 狭鳕  三文鱼  鱿鱼 虾  蟹 扇贝 牡蛎壳 虾蟹壳 金枪鱼
              PS: AnimalOrigin_Cn.includes("鱼") || AnimalOrigin_Cn.includes("真鳕") 
              || AnimalOrigin_Cn.includes("狭鳕") || AnimalOrigin_Cn.includes("三文鱼") 
              || AnimalOrigin_Cn.includes("鱿鱼") || AnimalOrigin_Cn.includes("虾") 
              || AnimalOrigin_Cn.includes("蟹") || AnimalOrigin_Cn.includes("扇贝") 
              || AnimalOrigin_Cn.includes("牡蛎壳") || AnimalOrigin_Cn.includes("虾蟹壳") || AnimalOrigin_Cn.includes("金枪鱼"),      //鱼 真鳕 狭鳕  三文鱼  鱿鱼 虾  蟹 扇贝 牡蛎壳 虾蟹壳 金枪鱼
              DF: AnimalOrigin_Cn.includes("蛋粉") || AnimalOrigin_Cn.includes("牡蛎壳") || AnimalOrigin_Cn.includes("虾蟹壳") ,      //蛋粉  牡蛎壳  虾蟹壳
              PAY:AnimalOrigin_Cn.includes("鱿鱼") || AnimalOrigin_Cn.includes("扇贝") || AnimalOrigin_Cn.includes("牡蛎壳"),      //鱿鱼  扇贝 牡蛎壳
              MS:AnimalOrigin_Cn.includes("兔"),  //兔
              MR:AnimalOrigin_Cn.includes("兔"),  //兔

            };
            datadetail.push(tempinfo);
          }

          let postData = {
            data: {
              info: {
                id: dataid,
                templateUrl: record.templateurl,
              },
              data: datadetail,
            },
          };
          console.log("postData", postData);
          let req_data = {
            arguments: JSON.stringify(postData),
          };
          console.log("req_data", req_data);
          var result = await window.ZOHO.CRM.FUNCTIONS.execute(
            "printdata",
            req_data
          );
          if (
            result &&
            result.code &&
            result.code.toString() === "success" &&
            result.details &&
            result.details.output
          ) {
            var output = JSON.parse(result.details.output);
            if (output.code && output.code.toString() === "200") {
              let openurl = output.data;;
              window.open(openurl, "_blank");

              // var base64data = output.data;
              // var byteCharacters = atob(base64data);
              // var byteNumbers = new Array(byteCharacters.length);
              // for (var i = 0; i < byteCharacters.length; i++) {
              //   byteNumbers[i] = byteCharacters.charCodeAt(i);
              // }
              // var byteArray = new Uint8Array(byteNumbers);

              // var blob = new Blob([byteArray], { type: "application/pdf" });
              // var blobUrl = window.URL.createObjectURL(blob);
              // window.open(blobUrl, "_blank");
            } else {
              message.error("发生错误，请联系管理员！");
            }
          }
        } else {
          message.info(
            "当前发票号不符合匹配规则，请修改拟证用发票号后再进行操作！"
          );
        }
      }
    } catch {
      message.error(`发生错误！首先请检查发票号和动物源性，然后联系管理员！`);
    }
  };
  const extractBakValues = (obj, key) => {
    // 检查是否存在 'LinkingModule21' 数组
    const linkingModule21 = obj.LinkingModule21;

    // 如果存在 'LinkingModule21'，则提取所有 'Bak' 值，并去掉空值
    if (Array.isArray(linkingModule21)) {
      return linkingModule21
        .map((item) => item[key]) // 提取 Bak 值
        .filter((value) => value !== null && value !== ""); // 去掉空值
    }
    // 如果 'LinkingModule21' 不存在或不是数组，返回空数组
    return [];
  };

  // 定义一个异步函数，用于打印发票
  const depprint_sumarryinvoice = async (record) => {
    try {
      // 根据实体名称和数据ID获取CRM记录
      var recorddata = await getCrmRecordById(Entityname, dataid);
      console.log("recorddata", recorddata);
      // 如果记录存在
      if (recorddata) {
        // 获取账户ID和发货人信息ID
        let accountid = recorddata.Account?.id;
        let shipperinformationid = recorddata.ShipperInformation?.id;
        // 根据账户ID获取账户信息
        let accountinfos = await window.ZOHO.CRM.API.getRecord({
          Entity: "Accounts",
          approved: "both",
          RecordID: accountid,
        });
        // 根据发货人信息ID获取发货人信息
        let shipperinformations = await window.ZOHO.CRM.API.getRecord({
          Entity: "ShipperInformation",
          approved: "both",
          RecordID: shipperinformationid,
        });
        // 获取账户信息和发货人信息
        let accountinfo = accountinfos?.data[0];
        let shipperinformation = shipperinformations?.data[0];
        console.log("accountinfo", accountinfo);
        console.log("shipperinformation", shipperinformation);

        // 获取子表信息
        let DeclarationSubfrom = recorddata.Subform_Detail;
        console.log("DeclarationSubfrom", DeclarationSubfrom);
        // 如果子表信息存在
        if (DeclarationSubfrom.length > 0) {
          // 获取分组数组
          var groupbyarrray = record.groupbyarrray;

          // 根据分组数组对子表信息进行分组
          const groupjson = groupBy(
            DeclarationSubfrom,
            groupbyarrray,
            "DeclarationSubfrom"
          );
          console.log("groupjson", groupjson);
          // 遍历分组后的数据
          groupjson.forEach((gitem) => {
            // 获取发货人信息
            gitem.China_Name = shipperinformation.China_Name || "";
            gitem.Name_En = shipperinformation.Name_En || "";
            gitem.Address_En = shipperinformation.Address_En || "";
            // 获取账户信息
            gitem.FullName = accountinfo.FullName || "";
            gitem.Addressfordocuments = accountinfo?.Addressfordocuments || "";
            // 获取发票信息
            gitem.Name = recorddata.Name || "";
            gitem.Date = formatDateToUpper(recorddata.InvoiceDate) || "";
            gitem.FcontractNos = recorddata.FcontractNos || "";
            gitem.VesselVoyage = recorddata.VesselVoyage || "";
            gitem.ShippingPort = recorddata.ShippingPort?.name || "";
            gitem.DestinationPort = recorddata.DestinationPort?.name || "";
            gitem.ShippingMarkAll = recorddata.ShippingMarkAll || "N/M";
            gitem.AllContractItem = recorddata.AllContractItem || "";
            gitem.AccountOrderNo = recorddata.AccountOrderNo || "";
            gitem.shipmentTerms = recorddata.shipmentTerms || "";
            gitem.TransactionMethod = recorddata.TransactionMethod || "";
            gitem.ETD = recorddata.ETD
              ? `ETD: ${formatDateToUpper(recorddata.ETD)}`
              : "";
            gitem.ETA = recorddata.ETA
              ? `ETA: ${formatDateToUpper(recorddata.ETA)}`
              : "";
            // 如果recorddata对象中有invoiceTerms属性，则将其值赋给gitem对象的invoiceTerms属性，否则将空字符串赋给gitem对象的invoiceTerms属性
            gitem.invoiceTerms = recorddata.invoiceTerms
              ? `${recorddata.invoiceTerms}`
              : "";

            // 获取包装单位
            let packaginunit = gitem.DeclarationSubfrom.find(
              (item) =>
                item.Packaginunit &&
                item.Packaginunit.trim() !== null &&
                item.Packaginunit.trim() !== ""
            )?.Packaginunit;

            console.log("DeclarationSubfrom", gitem.DeclarationSubfrom);
            // 按照 ContainerNumber 分组，并计算 NumberofCartons_sum 和 SalesAmount_sum，拼接去重的 OrderNo
            let groupedData = {};

            gitem.DeclarationSubfrom.forEach((item) => {
              const {
                ContainerNumber,
                NumberofCartons,
                SalesAmount,
                OrderNo,
              } = item;

              if (!groupedData[ContainerNumber]) {
                groupedData[ContainerNumber] = {
                  ContainerNumber,
                  NumberofCartons_sum: 0,
                  SalesAmount_sum: 0,
                  OrderNosum: new Set(),
                };
              }

              groupedData[
                ContainerNumber
              ].NumberofCartons_sum += NumberofCartons;
              groupedData[ContainerNumber].SalesAmount_sum += SalesAmount;
              groupedData[ContainerNumber].OrderNosum.add(OrderNo);
            });

            // 将分组后的数据转换为数组格式
            let groupedArray = Object.values(groupedData).map((group) => ({
              ContainerNumber: group.ContainerNumber,
              NumberofCartons_sum: parseFloat(
                group.NumberofCartons_sum.toFixed(2)
              ),
              SalesAmount_sum: parseFloat(group.SalesAmount_sum.toFixed(2)),
              OrderNosum: Array.from(group.OrderNosum).join("/"),
            }));

            // 设置发票信息
            gitem.field13 = `${parseFloat(
              groupedArray
                .reduce((sum, item) => sum + (item.NumberofCartons_sum || 0), 0)
                .toFixed(2)
            )}${packaginunit}S`;
            let SalesAmount_sum = parseFloat(
              groupedArray
                .reduce((sum, item) => sum + (item.SalesAmount_sum || 0), 0)
                .toFixed(2)
            );

            gitem.field2 = `${recorddata?.Currency} ${SalesAmount_sum}`;
            gitem.paymentAmount = `${numberToEnglish(SalesAmount_sum)}`;

            // 设置子表信息
            groupedArray.forEach((item) => {
              item.NumberofCartons_sum = `${item.NumberofCartons_sum}${packaginunit}S`;
              item.SalesAmount_sum = `${recorddata?.Currency} ${item.SalesAmount_sum}`;
            });

            gitem.DeclarationSubfrom = groupedArray;
          });


          
          // 构造要发送的数据
          let postData = {
            data: {
              info: {
                id: dataid,
                templateUrl: record.templateurl,
              },
              data: groupjson,
            },
          };
          console.log("postData", postData);

          // 构造请求参数
          let req_data = {
            arguments: JSON.stringify(postData),
          };
          // 执行函数
          var result = await window.ZOHO.CRM.FUNCTIONS.execute(
            "printdata",
            req_data
          );
          console.log("result", result);
          // 如果函数执行成功
          if (
            result &&
            result.code &&
            result.code.toString() === "success" &&
            result.details &&
            result.details.output
          ) {
            // 解析输出结果
            var output = JSON.parse(result.details.output);
            // 如果输出结果成功
            if (output.code && output.code.toString() === "200") {
              let openurl = output.data;;
              window.open(openurl, "_blank");

              // // 获取base64数据
              // var base64data = output.data;
              // // 将base64数据转换为字节数组
              // var byteCharacters = atob(base64data);
              // var byteNumbers = new Array(byteCharacters.length);
              // for (var i = 0; i < byteCharacters.length; i++) {
              //   byteNumbers[i] = byteCharacters.charCodeAt(i);
              // }
              // var byteArray = new Uint8Array(byteNumbers);

              // // 将字节数组转换为Blob对象
              // var blob = new Blob([byteArray], { type: "application/pdf" });
              // // 创建Blob URL
              // var blobUrl = window.URL.createObjectURL(blob);
              // // 打开PDF
              // window.open(blobUrl, "_blank");
            } else {
              // 如果输出结果失败，提示错误信息
              message.error("发生错误，请联系管理员！");
            }
          }
        }
      }
    } catch (error) {
      // 如果发生错误，提示错误信息
      message.error(`Failed to open PDF: ${error.message}`);
      console.error("Error fetching PDF:", error);
    } finally {
      // 设置加载状态为false
      setLoading(false);
    }
  };
  //分页逻辑
  const depprint = async (record) => {
    try {
      var recorddata = await getCrmRecordById(Entityname, dataid);

      console.log("recorddata", recorddata);
      if (recorddata) {
        let accountid = recorddata.Account?.id;
        let shipperinformationid = recorddata.ShipperInformation?.id;
        let accountinfos = await window.ZOHO.CRM.API.getRecord({
          Entity: "Accounts",
          approved: "both",
          RecordID: accountid,
        });
        let shipperinformations = await window.ZOHO.CRM.API.getRecord({
          Entity: "ShipperInformation",
          approved: "both",
          RecordID: shipperinformationid,
        });
        let accountinfo = accountinfos?.data[0];
        let shipperinformation = shipperinformations?.data[0];
        console.log("accountinfo", accountinfo);
        console.log("shipperinformation", shipperinformation);

        let DeclarationSubfrom = recorddata.Subform_Detail;
        console.log("DeclarationSubfrom", DeclarationSubfrom);
        if (DeclarationSubfrom.length > 0) {
          var groupbyarrray = record.groupbyarrray;

          const groupjson = groupBy(
            DeclarationSubfrom,
            groupbyarrray,
            "DeclarationSubfrom"
          );
          // console.log("groupjson", groupjson);
          groupjson.forEach((gitem) => {
            gitem.China_Name = shipperinformation.China_Name || "";
            gitem.Name_En = shipperinformation.Name_En || "";
            gitem.Address_En = shipperinformation.Address_En || "";
            gitem.FullName = accountinfo.FullName || "";
            gitem.Addressfordocuments = accountinfo?.Addressfordocuments || "";
            gitem.Name = recorddata.Name || "";
            gitem.Date = formatDateToUpper(recorddata.InvoiceDate) || "";
            gitem.FcontractNos = recorddata.FcontractNos || "";
            gitem.VesselVoyage = recorddata.VesselVoyage || "";
            gitem.ShippingPort = recorddata.ShippingPort?.name || "";
            gitem.DestinationPort = recorddata.DestinationPort?.name || "";
            gitem.ShippingMarkAll = recorddata.ShippingMarkAll || "N/M";
            gitem.AllContractItem = recorddata.AllContractItem || "";
            gitem.AccountOrderNo = recorddata.AccountOrderNo || "";
            gitem.shipmentTerms = recorddata.shipmentTerms || "";
            gitem.shippingDocumentTerms = recorddata.shippingDocumentTerms || "";
            
            gitem.TransactionMethod = recorddata.TransactionMethod || "";
            gitem.ETD = recorddata.ETD
              ? `ETD: ${formatDateToUpper(recorddata.ETD)}`
              : "";
            gitem.ETA = recorddata.ETA
              ? `ETA: ${formatDateToUpper(recorddata.ETA)}`
              : "";
            // 如果recorddata对象中有invoiceTerms属性，则将其值赋给gitem对象的invoiceTerms属性，否则将空字符串赋给gitem对象的invoiceTerms属性
            gitem.invoiceTerms = recorddata.invoiceTerms
              ? `${recorddata.invoiceTerms}`
              : "";
            gitem.shipmentTerms = recorddata.shipmentTerms
            ? `${recorddata.shipmentTerms}`
            : "";
            let groupedData = {};
            gitem.DeclarationSubfrom.forEach((subItem) => {
              let orderNo = subItem.OrderNo;
              if (!groupedData[orderNo]) {
                groupedData[orderNo] = [];
              }
              groupedData[orderNo].push(subItem);
            });

            // Step 2: 处理每个组
            let updatedDeclarationSubfrom = [];
            for (let orderNo in groupedData) {
              let group = groupedData[orderNo];

              // 将 NumberofCartons 为 0 的项移动到组的末尾
              let zeroCartonsItems = group.filter(
                (i) => i.NumberofCartons === 0
              );
              let nonZeroCartonsItems = group.filter(
                (i) => i.NumberofCartons !== 0
              );
              group = [...nonZeroCartonsItems, ...zeroCartonsItems];

              // 设置 ispo 属性
              if (group.length > 0) {
                group[0].ispo = true;
                for (let i = 1; i < group.length; i++) {
                  group[i].ispo = false;
                }
              }

              // 合并处理后的组数据
              updatedDeclarationSubfrom = [
                ...updatedDeclarationSubfrom,
                ...group,
              ];
            }
            //如果是箱单，去除折扣数据
            if (!record.isshowdis) {
              updatedDeclarationSubfrom = updatedDeclarationSubfrom.filter(
                (item) => item.NumberofCartons !== 0
              );
            }

            //处理客户货号
            let orderNos = [
              ...new Set(updatedDeclarationSubfrom.map((item) => item.OrderNo)),
            ];
            // 将数组元素用逗号连接成字符串
            gitem.OrderNos = `P.O.NO:${orderNos.join("/")}`;
            // 更新 DeclarationSubfrom
            gitem.DeclarationSubfrom = updatedDeclarationSubfrom;
            let firstUnit =
              updatedDeclarationSubfrom.length > 0
                ? updatedDeclarationSubfrom[0].Unit
                : null;
            let firstPackaginunit =
              updatedDeclarationSubfrom.length > 0
                ? updatedDeclarationSubfrom[0].Packaginunit
                : null;

            let Qtysum = parseFloat(
              updatedDeclarationSubfrom
                .reduce((sum, item) => sum + (item.Qty || 0), 0)
                .toFixed(2)
            );
            gitem.field12 = `${Qtysum} ${firstUnit}S`;
            let NumberofCartonssum = parseFloat(
              updatedDeclarationSubfrom
                .reduce((sum, item) => sum + (item.NumberofCartons || 0), 0)
                .toFixed(2)
            );
            gitem.field13 = `${NumberofCartonssum} ${firstPackaginunit}S`;
            gitem.TotalGrossWeight = `${parseFloat(
              updatedDeclarationSubfrom
                .reduce((sum, item) => sum + (item.TotalGrossWeight || 0), 0)
                .toFixed(2)
            )}KGS`;
            let sumSalesAmount = parseFloat(
              updatedDeclarationSubfrom
                .reduce((sum, item) => sum + (item.SalesAmount || 0), 0)
                .toFixed(2)
            );
            gitem.field2 = `${recorddata?.Currency} ${sumSalesAmount}`;
            gitem.paymentAmount = `${recorddata?.Currency} ${numberToEnglish(
              sumSalesAmount
            )}`;
            gitem.TotalVolume = `${parseFloat(
              updatedDeclarationSubfrom
                .reduce((sum, item) => sum + (item.TotalVolume || 0), 0)
                .toFixed(2)
            )}CBM`;
            gitem.TotalNetWeight = `${parseFloat(
              updatedDeclarationSubfrom
                .reduce((sum, item) => sum + (item.TotalNetWeight || 0), 0)
                .toFixed(2)
            )}KGS`;
            gitem.NumberofCartonssumUP = `${numberToEnglish(
              NumberofCartonssum
            )} ${firstPackaginunit}S  ONLY`;

            //处理单位空值问题
            // updatedDeclarationSubfrom
            updatedDeclarationSubfrom.forEach((item) => {
              if (item.NumberofCartons !== 0) {
                item.Unit += "S";
                item.Unit_Price = `${recorddata?.Currency} ${item.Unit_Price}`;
                item.Packaginunit += "S";
                item.TotalGrossWeight += "KGS";
                item.TotalVolume += "CBM";
                item.TotalNetWeight += "KGS";
                item.SalesAmount = `${recorddata?.Currency} ${item.SalesAmount}`;
              } else {
                item.Qty = null;
                item.Unit = null;
                item.NumberofCartons = null;
                item.TotalGrossWeight = null;

                item.TotalNetWeight = null;
              }
            });
          });
          let postData = {
            data: {
              info: {
                id: dataid,
                templateUrl: record.templateurl,
              },
              data: groupjson,
            },
          };
          console.log("postData", postData);

          let req_data = {
            arguments: JSON.stringify(postData),
          };
          var result = await window.ZOHO.CRM.FUNCTIONS.execute(
            "printdata",
            req_data
          );
          console.log("result", result);
          if (
            result &&
            result.code &&
            result.code.toString() === "success" &&
            result.details &&
            result.details.output
          ) {
            var output = JSON.parse(result.details.output);
            if (output.code && output.code.toString() === "200") {
              let openurl = output.data;;
              window.open(openurl, "_blank");
              // var base64data = output.data;
              // var byteCharacters = atob(base64data);
              // var byteNumbers = new Array(byteCharacters.length);
              // for (var i = 0; i < byteCharacters.length; i++) {
              //   byteNumbers[i] = byteCharacters.charCodeAt(i);
              // }
              // var byteArray = new Uint8Array(byteNumbers);

              // var blob = new Blob([byteArray], { type: "application/pdf" });
              // var blobUrl = window.URL.createObjectURL(blob);
              // window.open(blobUrl, "_blank");
            } else {
              message.error("发生错误，请联系管理员！");
            }
          }
        } else {
          message.warning("此条数据没有行明细数据，请核对后再进行操作！");
        }
      } else {
        message.error("获取页面数据失败！");
      }
    } catch (error) {
      message.error(`Failed to open PDF: ${error.message}`);
      console.error("Error fetching PDF:", error);
    } finally {
      setLoading(false);
    }
  };

  //点击主要逻辑
  const handleClick = async (record) => {
    setLoading(true);
    try {
      if (record?.isdep) {
        if (record?.id === 122222221) {
          console.log("--------开始拟证-----------");
          await antiepidemic_print(record);
        } else if (record?.id === 622222221) {
          console.log("--------开始发票-清关发票-SUMARRY INVOICE-----------");
          await depprint_sumarryinvoice(record);
        } else {
          await depprint(record);
        }
      } else {
        //系统自带的主逻辑
        var filename = `${record.filename}${dataid}.pdf`;
        let req_data = {
          arguments: JSON.stringify({
            entityname: Entityname,
            dataid: dataid[0],
            templateid: record.id,
            filename: filename,
          }),
        };

        const filedata = await window.ZOHO.CRM.FUNCTIONS.execute(
          "mailmergeshow",
          req_data
        );

        if (filedata && filedata.details && filedata.details.output) {
          var strdata = filedata.details.output;
          var jsondata = JSON.parse(strdata);
          var pdfurl = jsondata?.data[0].attributes?.Permalink;
          console.log(pdfurl);
          // 提取文件 ID
          const fileId = pdfurl.split("/").pop();

          // 构建新的 URL
          const printurl = `https://workdrive.zoho.com.cn/print/${fileId}`;
          window.open(printurl, "_blank");
        }
      }
    } catch (error) {
      message.error(`Failed to open PDF: ${error.message}`);
      console.error("Error fetching PDF:", error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <ConfigProvider
    theme={{
      components: {
        Collapse: {
          contentPadding: "4px 14px"
        },
      }
    }}
    >
    <div style={{ position: "relative", minHeight: "100vh" }}>
      {loading ? (
        <div
          style={{
            display: "flex",
            justifyContent: "center",
            alignItems: "center",
            height: "100vh",
          }}
        >
          <Spin />
        </div>
      ) : (
          <Collapse accordion defaultActiveKey={[0]}>
            {Object.keys(groupedTemplates).map((folderName, index) => (
              <Panel header={folderName} key={index} className="custom-panel" >
                <List
                  dataSource={groupedTemplates[folderName]}
                  renderItem={(item) => (
                    <List.Item
                      onClick={() => handleClick(item)}
                      style={{
                        cursor: "pointer",
                        fontSize: "15px",
                        display: "flex",
                        alignItems: "center",
                        height: "35px",
                        backgroundColor:
                          item.id === selectedRow ? "#e6f7ff" : "transparent",
                      }}
                      onMouseEnter={() => setSelectedRow(item.id)}
                      onMouseLeave={() => setSelectedRow(null)}
                    >
                      {item.isdep ? item.name : item.filename}
                    </List.Item>
                  )}
                />
              </Panel>
            ))}
          </Collapse>
      )}
    </div>
    </ConfigProvider>
  );
};

export default App;
